<template>
  <div class="app-container">
    <div class="customContainer">
      <!-- 搜索头 -->
      <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
        <el-form-item>
          <el-input v-model="formInline.name" placeholder="搜索分组" @keyup.enter.native="searchClick"></el-input>
        </el-form-item>
        <el-form-item>
          <dj-button size="small" @search="searchClick">
            <template #default>搜索</template>
          </dj-button>
        </el-form-item>
      </el-form>
      <!-- 列表 -->
      <el-table highlight-current-row :data="list" v-loading.body="listLoading" border fit size="small">
        <el-table-column align="center" label="序号" width="50">
          <template slot-scope="scope">
            <span class="indexColor">{{scope.$index+1+(currentPage-1)*20}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="分组名称" prop="name"></el-table-column>
        <el-table-column align="center" label="描述" prop="intro"></el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" plain size="mini" @click="getIndex(scope.row)">配置首页</el-button>
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="onAuthgroupEditClick(list[scope.$index]['id'])"></el-button>
            <el-button type="primary" size="mini" @click="showUserList(scope.row.id)">
              <svg-icon icon-class="user" />
            </el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="onAuthgroupDeleteClick(list[scope.$index]['id'])"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 权限组编辑&新增权限组弹框 权限维护 -->
    <el-dialog :close-on-click-modal="false" width="80%" class="dialog_table" style="margin-top:-5vh;" title="权限维护" :visible.sync="authDialog">
      <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
        <el-form-item label="分组名称" style="width: 40%;">
          <el-input v-model="saveForm.name" placeholder="分组名称"></el-input>
        </el-form-item>
        <el-form-item label="描述" style="width: 50%;">
          <el-input type="textarea" v-model="saveForm.intro" placeholder="描述" style="width:300px"></el-input>
        </el-form-item>
      </el-form>
      <!-- 权限分类单项切换 -->
      <el-radio-group v-model="authTypeRadio" @change="onAuthTypeRadioChanged">
        <el-radio label="pc">PC</el-radio>
        <el-radio label="web">Web</el-radio>
        <el-radio label="app">App</el-radio>
      </el-radio-group>
      <br />
      <br />
      <!-- 权限tap标签分类 -->
      <el-tabs v-model="authTreeTapName" @tab-click="onAuthTreeTapClick" style="width:100%;">
        <el-tab-pane v-for="(itemtop, idxtop) in authtaps" :id="itemtop.id" :key="idxtop" :label="itemtop.name" :name="itemtop.name"></el-tab-pane>
      </el-tabs>
      <!-- 通过table合并某些行，绘制权限树 -->
      <el-table highlight-current-row :data="tableData" :span-method="objectSpanMethod" border :show-header="false" size="mini" style="width:100%;">
        <el-table-column v-for="(item, idx) in columnList" :key="idx">
          <template slot-scope="scope">
            <!-- checkbox表示具体的权限，可以选中或取消权限 -->
            <el-checkbox @change="ckchanged(tableData, scope.$index, item)" v-model="tableData[scope.$index][item].status" size="mini">
              {{ tableData[scope.$index][item].name }}</el-checkbox>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <!-- 权限组编辑或新增保存按钮 -->
        <el-button type="primary" @click="saveClick()" size="small">保 存</el-button>
      </div>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" width="30%" title="用户列表" :visible.sync="userListDialog">
      <el-button type="text" v-for="item in userList" :key="item.id" @click="getUserClick(item.nick)">{{ item.nick }}
      </el-button>
    </el-dialog>
    <!-- 配置首页 -->
    <el-dialog :close-on-click-modal="false" width="400px" title="配置首页" :visible.sync="indexDialog">
      <el-table highlight-current-row :data="indexList" border fit size="small">
        <el-table-column align="center" :render-header="renderHeader" width="80">
          <template slot-scope="scope">
            <el-checkbox v-model="scope.row.isCheck"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column align="center" label="图表" prop="name"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveIndex" size="small">保 存</el-button>
      </div>
    </el-dialog>
    <!-- 自定义底部 -->
    <div class="bottom_box">
      <el-pagination class="pull-left" background @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="20"
        layout="prev, pager, next, jumper" :total="totalDataNumber"></el-pagination>
      <el-button class="pull-right" type="primary" size="small" @click="onAuthgroupAddClick">新增权限组</el-button>
    </div>
  </div>
</template>
<script>
import {
  getList,
  getPage,
  getAuthgoupInfo,
  saveAuthgroup,
  addAuthgroup,
  delAuthgroup,
  getUserList,
  getIndexList,
  setIndexList
} from '@/api/setting/auth_manager';
export default {
  data() {
    return {
      authTreeTapName: '', //指示当前权限树Tap标签
      authTypeRadio: 'pc', //指示当前权限分类单选选中
      list: null,
      listLoading: false,
      userListDialog: false, //用户列表弹框
      indexDialog: false, //配置首页弹框
      userList: [], //权限用户列表
      authDialog: false, //指示权限组编辑&新增权限组弹框是否弹出展示
      currentPage: 1, //指示当前所在分页
      totalDataNumber: 0,
      saveForm: {
        name: '',
        intro: '',
        auth_id: '' //1,2,3,4,5,70,76,87,244
      },
      formInline: {
        name: ''
      },
      authgroup_id: 0, //指示权限组编辑&新增权限组弹框对应的权限组id，新增权限组时该值为0
      authgroup_initial_name: '', //指示服务器获得的权限组名称，新增权限组时该值为空
      authgroup_initial_intro: '', //指示服务器获得的权限组介绍，新增权限组时该值为空
      auth_initial_flags: [], //指示服务器获得的权限组中权限的选中情况，key为权限id，value为true表示拥有该权限
      auth_modify_flags: [], //指示用户编辑后的权限组中权限的选中情况，key为权限id，value为true表示拥有该权限
      authgoupinfo: [], //指示服务器获得的权限组中所有的权限数据
      authlist: [], //用于临时存储权限分类（pc，web，app）对应的所有选项
      authtaps: [], //权限树Tap标签列表
      colsize: 0, //表示当前权限树的最大深度，及table的列数
      0: this.columnList, //权限树table中的列数据
      1: this.tableData, //权限树绘制数据
      2: this.column_row_offset, //用户生成并绘制权限树table
      6: this.authtreelist, //权限树原始数据
      indexList: [{ id: 1, name: '今日概况', isCheck: false }], //配置首页弹窗表数据
      allCheck: 0, //配置首页全选
      category_id: '' //配置首页权限id
    };
  },
  //再界面绘制前定义并初始化相关变量，防止checkbox点击失效
  beforeCreate() {
    this.authtreelist = [];
    this.columnList = [];
    this.tableData = [];
    this.column_row_offset = [];
    for (var ii = 0; ii < 1; ii++) {
      this.columnList[ii] = [];
    }
    for (var i = 0; i < 1; i++) {
      this.tableData[i] = [];
      for (let j = 0; j < 1; j++) {
        this.tableData[i][j] = {};
        this.tableData[i][j].name = '';
        this.tableData[i][j].status = true;
        this.tableData[i][j].id = 0;
        this.tableData[i][j].parent_id = 0;
      }
    }
  },
  created() {
    this.fetchData();
  },

  methods: {
    // 跳转用户
    getUserClick(nick) {
      this.$router.push({
        // path: '/user_manager/user_list/',
        name: 'setting/user_list',
        params: {
          nick: nick
        }
      });
      this.userListDialog = false;
    },
    // 用户列表弹框
    showUserList(id) {
      this.userList = [];
      getUserList({ id: id }).then(response => {
        this.userList = response;
        this.userListDialog = true;
      });
    },
    //新增或编辑权限组时，保存按钮点击触发
    saveClick() {
      // console.log(this.auth_initial_flags);
      // console.log(this.auth_modify_flags);
      var addauth = '';
      var delauth = '';
      for (var key in this.auth_modify_flags) {
        if (this.auth_initial_flags[key] != this.auth_modify_flags[key]) {
          // console.log(this.auth_initial_flags[key]);
          if (this.auth_modify_flags[key]) {
            addauth += addauth == '' ? key : ',' + key;
          } else {
            delauth += delauth == '' ? key : ',' + key;
          }
        }
      }

      if (this.authgroup_id == 0) {
        //新增权限组
        //addAuth
        if (this.saveForm.name == '' || this.saveForm.intro == '') {
          this.$message({
            type: 'warning',
            message: '请填写权限组名称和描述'
          });
          return;
        }
        var data = {
          name: this.saveForm.name,
          intro: this.saveForm.intro,
          auth_id: addauth
        };

        addAuthgroup(data).then(response => {
          this.$message({
            type: response.code == 1 ? 'success' : 'error',
            message: response.message
          });
          if (response.code == 1) {
            this.authDialog = false;
            this.gotoLastPage();
          }
        });
      } else {
        //修改权限组
        if (this.saveForm.name == this.authgroup_initial_name && this.saveForm.intro == this.authgroup_initial_intro && addauth == '' && delauth == '') {
          this.$message({
            type: 'info',
            message: '没有做任何修改'
          });
          return;
        }

        var data2 = {
          id: this.authgroup_id,
          name: this.saveForm.name,
          intro: this.saveForm.intro,
          auth_add: addauth,
          auth_del: delauth
        };

        saveAuthgroup(data2).then(response => {
          this.$message({
            type: response.code == 1 ? 'success' : 'error',
            message: response.message
          });
          if (response.code == 1) {
            this.authDialog = false;
          }
        });
      }
    },
    //删除权限组触发
    onAuthgroupDeleteClick(authgroup_id) {
      this.$confirm('确定删除该权限组?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delAuthgroup(authgroup_id).then(response => {
          this.$message({
            type: response.code == 1 ? 'success' : 'error',
            message: response.message
          });
          if (response.code == 1) {
            this.handleCurrentChange(this.currentPage);
          }
        });
      });
    },
    //编辑权限组按钮点击触发，打开权限组编辑弹框
    onAuthgroupEditClick(authgroup_id) {
      this.authgroup_id = authgroup_id;
      this.authtaps = [];
      this.authlist = [];
      this.auth_initial_flags = [];
      this.auth_modify_flags = [];
      //请求获取权限组数据
      getAuthgoupInfo({ id: this.authgroup_id }).then(response => {
        this.authgoupinfo = response.auth;
        for (let i = 0; i < this.authgoupinfo.length; i++) {
          this.authgoupinfo[i].is_view *= 1;
          this.authgoupinfo[i].is_web *= 1;
          this.authgoupinfo[i].parent_id *= 1;
          this.authgoupinfo[i].right *= 1;
          this.auth_initial_flags[this.authgoupinfo[i].id] = this.authgoupinfo[i].right == 1 ? true : false;
          this.authgoupinfo[i].id *= 1;
        }
        // console.log(this.auth_initial_flags);
        this.authgroup_initial_name = response.name;
        this.authgroup_initial_intro = response.intro;
        this.saveForm.name = response.name;
        this.saveForm.intro = response.intro;
        for (let i = 0; i < this.authgoupinfo.length; i++) {
          if (this.authgoupinfo[i]['is_web'] == 0) {
            this.authlist.push(this.authgoupinfo[i]);
          }
        }
        for (let i = 0; i < this.authlist.length; i++) {
          if (this.authlist[i]['parent_id'] == 0) {
            this.authtaps.push({
              id: this.authlist[i]['id'],
              name: this.authlist[i]['name']
            });
          }
        }
        //初始化radio，tap选择，生成对应权限树界面
        this.authTypeRadio = 'pc';
        this.authTreeTapName = this.authtaps[0].name;
        this.makeAuthTree(this.authtaps[0].id);
      });
      this.authDialog = true;
    },
    //配置首页
    getIndex(row) {
      this.indexList = [];
      getIndexList({ group_id: row.id }).then(res => {
        if (res.code == 1) {
          let list = [];
          let id = 1;
          let obj = res.message.category;
          this.category_id = res.message.id;
          this.authgroup_id = row.id;
          Object.keys(obj).forEach(key => {
            list.push({ id: id++, name: key, isCheck: obj[key] == 1 });
          });
          this.indexList = list;
        }
        this.indexDialog = true;
      });
    },
    saveIndex() {
      let category = '';
      this.indexList.forEach(val => {
        category += val.isCheck ? ',' + val.id : '';
      });
      category = category.slice(1);
      setIndexList({
        group_id: this.authgroup_id,
        id: this.category_id,
        category
      }).then(res => {
        this.$message({
          type: res.code == 1 ? 'success' : 'error',
          message: res.message
        });
        if (res.code == 1) {
          this.indexDialog = false;
        }
      });
    },
    //表头
    renderHeader(h, { column }) {
      var self = this;
      return h('el-checkbox', {
        style: 'font-size:12px;',
        props: { label: '全选', 'true-label': 1, value: self.allCheck == 1 },
        on: {
          change: (column, $event) => {
            if (self.allCheck == 1) {
              self.allCheck = 0;
              self.indexList.forEach(val => {
                val.isCheck = false;
              });
            } else {
              self.allCheck = 1;
              self.indexList.forEach(val => {
                val.isCheck = true;
              });
            }
          }
        }
      });
    },
    //点击新增权限组按钮触发
    onAuthgroupAddClick() {
      this.authgroup_id = 0; //新增权限组
      this.authtaps = [];
      this.authlist = [];
      this.auth_initial_flags = [];
      this.auth_modify_flags = [];
      //authgroup_id=0表示新增，仅仅获取权限树信息
      getAuthgoupInfo({ id: this.authgroup_id }).then(response => {
        // console.log(response);
        this.authgoupinfo = response.auth;
        for (let i = 0; i < this.authgoupinfo.length; i++) {
          this.authgoupinfo[i].is_view *= 1;
          this.authgoupinfo[i].is_web *= 1;
          this.authgoupinfo[i].parent_id *= 1;
          this.authgoupinfo[i].right *= 1;
          this.auth_initial_flags[this.authgoupinfo[i].id] = this.authgoupinfo[i].right == 1 ? true : false;
          this.authgoupinfo[i].id *= 1;
        }
        this.authgroup_initial_name = response.name;
        this.authgroup_initial_intro = response.intro;
        this.saveForm.name = response.name;
        this.saveForm.intro = response.intro;
        for (let i = 0; i < this.authgoupinfo.length; i++) {
          if (this.authgoupinfo[i]['is_web'] == 0) {
            this.authlist.push(this.authgoupinfo[i]);
          }
        }
        for (let i = 0; i < this.authlist.length; i++) {
          if (this.authlist[i]['parent_id'] == 0) {
            this.authtaps.push({
              id: this.authlist[i]['id'],
              name: this.authlist[i]['name']
            });
          }
        }
        this.authTypeRadio = 'pc';
        this.authTreeTapName = this.authtaps[0].name;
        this.makeAuthTree(this.authtaps[0].id);
      });
      this.authDialog = true;
    },
    //PC，Web，App分类单选框，单选变化触发，更新权限树界面
    onAuthTypeRadioChanged(value) {
      var type = 0;
      if (value == 'pc') {
        type = 0;
      } else if (value == 'web') {
        type = 1;
      } else if (value == 'app') {
        type = 2;
      } else {
        type = 3;
      }
      this.authtaps = [];
      this.authlist = [];
      for (let i = 0; i < this.authgoupinfo.length; i++) {
        if (this.authgoupinfo[i]['is_web'] == type) {
          this.authlist.push(this.authgoupinfo[i]);
        }
      }
      for (let i = 0; i < this.authlist.length; i++) {
        if (this.authlist[i]['parent_id'] == 0) {
          this.authtaps.push({
            id: this.authlist[i]['id'],
            name: this.authlist[i]['name']
          });
        }
      }
      this.authTreeTapName = this.authtaps[0].name;
      this.makeAuthTree(this.authtaps[0].id);
    },
    //权限树Tap标签被点击，刷新权限树权限
    onAuthTreeTapClick(tab, event) {
      // console.log(tab.$attrs.id);
      this.makeAuthTree(tab.$attrs.id);
    },
    //获取权限组列表数据
    // fetchData() {
    //   getList(this.formInline)
    //     .then(response => {
    //       this.list = response;
    //       this.listLoading = false;
    //     })
    //     .catch(res => {
    //       this.listLoading = false;
    //     });
    // },
    //创建权限树
    makeAuthTree(groupid) {
      this.colsize = 0;
      this.columnList.splice(0);
      this.authtreelist.splice(0);
      // console.log("1111");
      // for (let i = 0; i < this.tableData.length; i++) {
      //   this.tableData[i].pop();
      // }
      this.tableData = [];
      // console.log(this.tableData);

      for (let i = 0; i < this.authgoupinfo.length; i++) {
        if (this.authgoupinfo[i]['id'] == groupid) {
          this.authtreelist.push(this.authgoupinfo[i]);
          this.maketree(this.authgoupinfo[i]['id']);
          break;
        }
      }
      this.column_row_offset.splice(0);

      this.getauthtreeNode(0, 0, 0);
      for (var i = 0; i < this.colsize + 1; i++) {
        this.columnList[i] = '' + i;
      }
    },
    //递归创建权限树，内部方法
    maketree(parent_id) {
      for (let i = 0; i < this.authgoupinfo.length; i++) {
        if (this.authgoupinfo[i]['parent_id'] * 1 == parent_id * 1) {
          // console.log(this.authgoupinfo[i]['parent_id']+" ==== "+parent_id);
          // console.log(this.authgoupinfo[i]);
          this.authtreelist.push(this.authgoupinfo[i]);
          this.maketree(this.authgoupinfo[i]['id']);
        }
      }
    },

    //用户生成权限树table需要的数据格式，主要是tableData数据，计算colsize，column_row_offset等
    getauthtreeNode(parent_id, col, rowidx) {
      var row = 0;
      var tmp_offset = [];
      var tmp = 0;
      // var rowidx = 0;
      for (var i = 0; i < this.authtreelist.length; i++) {
        if (this.authtreelist[i]['parent_id'] * 1 == parent_id) {
          if (this.colsize < col) {
            this.colsize = col;
          }
          if (!this.column_row_offset[col]) {
            this.column_row_offset[col] = [];
          }
          if (tmp > 0) {
            if (this.column_row_offset[col][rowidx]) {
              rowidx += tmp;
              // rowidx += this.column_row_offset[col][rowidx];
            }
          } else {
            if (this.column_row_offset[col][rowidx]) {
              rowidx += 1;
            }
          }
          // console.log(this.authtreelist[i]['id'] + "  " + this.column_row_offset[col][rowidx] + "   " + col + "  " + rowidx);
          tmp = this.getauthtreeNode(this.authtreelist[i]['id'] * 1, col + 1, rowidx);
          // console.log(this.authtreelist[i]['id']+"  "+tmp +"   "+col+"  "+rowidx);

          if (tmp > 0) {
            row += tmp;
            this.column_row_offset[col][rowidx] = tmp;
          } else {
            row += 1;
            tmp = 1;
            this.column_row_offset[col][rowidx] = 1;
          }

          // console.log(this.authtreelist[i]['id'] + "  " + this.column_row_offset[col][rowidx] + "   " + col + "  " + rowidx);
          if (!this.tableData[rowidx]) {
            this.tableData[rowidx] = [];
          }
          for (let k = 0; k < this.column_row_offset[col][rowidx]; k++) {
            if (!this.tableData[rowidx + k][col]) {
              this.tableData[rowidx + k][col] = {};
            }
            if (
              this.auth_modify_flags.hasOwnProperty(this.authtreelist[i].id) &&
              this.auth_modify_flags[this.authtreelist[i].id] != (this.authtreelist[i].right == 1)
            ) {
              this.tableData[rowidx + k].splice(col, 1, {
                id: this.authtreelist[i].id * 1,
                parent_id: this.authtreelist[i].parent_id * 1,
                name: this.authtreelist[i].name,
                status: this.auth_modify_flags[this.authtreelist[i].id]
              });
            } else if (this.authtreelist[i].right == 1) {
              this.tableData[rowidx + k].splice(col, 1, {
                id: this.authtreelist[i].id * 1,
                parent_id: this.authtreelist[i].parent_id * 1,
                name: this.authtreelist[i].name,
                status: true
              });
            } else {
              this.tableData[rowidx + k].splice(col, 1, {
                id: this.authtreelist[i].id * 1,
                parent_id: this.authtreelist[i].parent_id * 1,
                name: this.authtreelist[i].name,
                status: false
              });
            }
          }
        }
      }
      return row;
    },
    //权限树中每个权限有checkbox构成，该方法表示某个权限CheckBox被点击
    ckchanged(data, row, col) {
      if (data[row][col].status) {
        this.auth_modify_flags[data[row][col].id] = true;
        //父节点选中
        this.updateParentStatus(data, data[row][col].parent_id * 1, col * 1 - 1);
      } else if (!data[row][col].status) {
        this.auth_modify_flags[data[row][col].id] = false;
        //子节点取消
        this.updateChildrenStatus(data, data[row][col].id * 1, col * 1 + 1);
      }
    },
    //递归触发子节点取消操作
    updateChildrenStatus(data, parent_id, col) {
      // console.log("col="+col+" parent_id="+parent_id);
      for (var i = 0; i < data.length; i++) {
        // console.log("i="+i+" data.length="+data.length);
        for (var j = col; j < data[i].length; j++) {
          // console.log("i="+i+" j="+j+" status="+data[i][j].status);
          if (data[i][j].parent_id * 1 == parent_id && data[i][j].status) {
            data[i][j].status = false;
            this.auth_modify_flags[data[i][j].id] = false;
            this.updateChildrenStatus(data, data[i][j].id * 1, col * 1 + 1);
          }
        }
      }
    },
    //递归触发父节点选中操作
    updateParentStatus(data, parent_id, col) {
      if (col < 0) return;
      // console.log("col=" + col + " parent_id=" + parent_id);
      for (let i = 0; i < data.length; i++) {
        // console.log("i=" + i + " data.length=" + data.length);
        if (col < data[i].length) {
          for (let j = col; j >= 0; j--) {
            // console.log("i=" + i + " j=" + j + " status="+data[i][j].status);
            if (data[i][j].id * 1 == parent_id && !data[i][j].status) {
              data[i][j].status = true;
              this.auth_modify_flags[data[i][j].id] = true;
              this.updateParentStatus(data, data[i][j].parent_id * 1, col * 1 - 1);
            }
          }
        }
      }
    },
    //权限树绘制，由表格绘制而成，该方法决定表格行合并
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (this.column_row_offset[columnIndex] && this.column_row_offset[columnIndex][rowIndex]) {
        return {
          rowspan: this.column_row_offset[columnIndex][rowIndex],
          colspan: 1
        };
      } else {
        return {
          rowspan: 0,
          colspan: 1
        };
      }
    },

    // 搜索
    searchClick() {
      this.fetchData();
    },
    // 列表获取
    fetchData() {
      this.listLoading = true;
      this.currentPage = 1;
      getPage(this.formInline).then(response => {
        this.totalDataNumber = response * 20;
        getList(this.formInline).then(response => {
          this.list = response;
          this.listLoading = false;
        });
      });
    },
    handleCurrentChange(val) {
      this.listLoading = true;
      getList(this.formInline, val).then(response => {
        this.list = response;
        this.listLoading = false;
      });
    },
    gotoLastPage() {
      this.handleCurrentChange((this.totalDataNumber + 1) / 20);
    }
  },
  computed: {
    isAllCheck: function() {
      return this.indexList.filter(val => val.isCheck == true).length == 8;
    }
  },
  watch: {
    isAllCheck: function(val) {
      this.allCheck = val ? 1 : 0;
    }
  }
};
</script>
<style scoped>
.dialog_table {
  min-width: 900px;
  max-width: 1600px;
  margin-top: -5vh;
}
</style>